package com.fingard.dsp.bank.directbank.lcbip01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;

/**
 * Created by F on 2018/9/12.
 */
public class LCBIP01Balance extends LCBIP01Base implements IBalance {

    /**
     * 查询余额
     *
     * @param p_req7506
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts7506BalQry = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts7506BalQry.writeStart();
        try {
            while (p_req7506.readRecord()) {
                RetAtsBalDetail detail = new RetAtsBalDetail();
                //非公有参数
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                //拼接请求报文
                LCBIP01Header header = new LCBIP01Header();
                header.TuxName = "Balance";
                header.ReqSeqNo = getQryTransID();
                writeCommonHeader(xmlTextWriter, header);
                xmlTextWriter.writeEndElement();
                //获取币种和账号
                XElement body = new XElement("body", "");
                body.addChild(new XElement("CustCode", bankFront.org));
                body.addChild(new XElement("AccNo", p_req7506.readedDetail.actNum));
                body.addChild(new XElement("AccContry", ""));
                body.addChild(new XElement("AccPriv", ""));
                body.addChild(new XElement("AccCity", ""));
                body.addChild(new XElement("CurType", convertCurToBank(p_req7506.readedDetail.actCur)));
                body.addChild(new XElement("HisDate", ""));
                xmlTextWriter.writeXElement(body);
                xmlTextWriter.writeEndDocument();
                //发送请求报文
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
                //处理响应报文
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSb = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSb);
                    if (tmpBkReader != null) {
                        String RespCode = tmpBkReader.getFirstText("/lcbank/head/RespCode");
                        String RespInfo = tmpBkReader.getFirstText("/lcbank/head/RespInfo");
                        if ("0".equals(RespCode)) {//交易成功
                            if (tmpBkReader.read("/lcbank/body")) {
                                detail.respCode = "0";
                                detail.respInfo = RespInfo;
                                detail.actCur = p_req7506.readedDetail.actCur;
                                detail.actNum = p_req7506.readedDetail.actNum;
                                detail.availBal = tmpBkReader.readedXElement.getSingleTextNotNull("AvailBal");
                                detail.currBal = tmpBkReader.readedXElement.getSingleTextNotNull("Bal");
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = RespInfo;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSb.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = bankResult[1];
                }
                retAts7506BalQry.writeRetDetail(detail, p_req7506.isBatch);
            }
        } catch (Exception e) {
            retAts7506BalQry.writeRespCode("-1");
            retAts7506BalQry.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts7506BalQry.writeEnd();
        return retAts7506BalQry;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        retAts.writeStart();
        String tmpRespCode = "";
        StringBuilder errormsg = new StringBuilder();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7505.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7505.getDateTo());

            int compareDay = DateHelper.compareDay(tmpCalendarTo.getTime(), tmpCalendarFrom.getTime());
            if (compareDay == -1) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("查询交易终止日期小于查询交易起始日期!");
                retAts.writeEnd();
                return retAts;
            }

            Calendar tmpCalendarTemp = Calendar.getInstance();
            tmpCalendarTemp.setTime(p_req7505.getDateFrom());

            //银行接口只支持一天一天去查询
            while (DateHelper.compareDay(tmpCalendarTo.getTime(), tmpCalendarTemp.getTime()) >= 0) {
                try {
                    //非公有参数
                    XmlTextWriter xmlTextWriter = new XmlTextWriter();
                    //拼接请求报文
                    LCBIP01Header header = new LCBIP01Header();
                    header.TuxName = "Balance";
                    header.ReqSeqNo = getQryTransID();
                    writeCommonHeader(xmlTextWriter, header);
                    xmlTextWriter.writeEndElement();
                    //获取币种和账号
                    XElement body = new XElement("body", "");
                    body.addChild(new XElement("CustCode", bankFront.org));
                    body.addChild(new XElement("AccNo", p_req7505.actNum));
                    body.addChild(new XElement("AccContry", ""));
                    body.addChild(new XElement("AccPriv", ""));
                    body.addChild(new XElement("AccCity", ""));
                    body.addChild(new XElement("CurType", convertCurToBank(p_req7505.actCur)));
                    String HisDate = Format.Date8Format.format(tmpCalendarTemp.getTime());
                    body.addChild(new XElement("HisDate", HisDate));
                    xmlTextWriter.writeXElement(body);
                    xmlTextWriter.writeEndDocument();

                    //发送请求报文
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
//                    String[] bankResult = {"", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
//                            "<lcbank>\n" +
//                            "    <head>\n" +
//                            "        <BankNo>50</BankNo>\n" +
//                            "        <TuxName>Balance</TuxName>\n" +
//                            "        <ReqSeqNo>48701551134</ReqSeqNo>\n" +
//                            "        <RespDate>20190606</RespDate>\n" +
//                            "        <RespTime>162552</RespTime>\n" +
//                            "        <RespCode>0</RespCode>\n" +
//                            "        <RespInfo>ceshi</RespInfo>\n" +
//                            "    </head>\n" +
//                            "    <body>\n" +
//                            "        <Bal>22737672.6</Bal>\n" +
//                            "        <AvailBal>22737672.6</AvailBal>\n" +
//                            "    </body>\n" +
//                            "</lcbank>"};
                    //处理响应报文
                    if (bankResult[0].length() == 0) {
                        StringBuilder tmpSb = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSb);
                        if (tmpBkReader != null) {
                            String RespCode = tmpBkReader.getFirstText("/lcbank/head/RespCode");
                            String RespInfo = tmpBkReader.getFirstText("/lcbank/head/RespInfo");
                            if ("0".equals(RespCode)) {//交易成功
                                if (tmpBkReader.read("/lcbank/body")) {
                                    RetAtsHisBalDetail detail = new RetAtsHisBalDetail();
                                    detail.actBal = tmpBkReader.readedXElement.getSingleTextNotNull("Bal");//历史余额
                                    detail.availBal = tmpBkReader.readedXElement.getSingleTextNotNull("AvailBal");//历史可用余额
                                    detail.balDate = Format.Date10Format.format(tmpCalendarTemp.getTime());
                                    retAts.writeRetDetail(detail);
                                }
                            } else {
                                tmpRespCode = "0";
                                errormsg.append("日期：" + Format.Date8Format.format(tmpCalendarTemp.getTime()) + "查询余额失败：" + RespInfo + "\r\n");
                            }
                        } else {
                            tmpRespCode = "-1";
                            errormsg.append("日期：" + Format.Date8Format.format(tmpCalendarTemp.getTime()) + "查询余额失败：" + tmpSb.toString() + "\r\n");
                        }
                    } else {
                        tmpRespCode = "-1";
                        errormsg.append("日期：" + Format.Date8Format.format(tmpCalendarTemp.getTime()) + "查询余额失败：" + bankResult[1] + "\r\n");
                    }
                } catch (Exception e) {
                    tmpRespCode = "-1";
                    errormsg.append("日期：" + Format.Date8Format.format(tmpCalendarTemp.getTime()) + "查询余额失败：" + e.getMessage() + "\r\n");
                }

                tmpCalendarTemp.setTime(DateHelper.addDays(tmpCalendarTemp.getTime(), 1));//日期+1
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            errormsg.append("查询出现异常,详情查看日志！\r\n");
            WriteBankLogLn("查询出现异常:" + e.getMessage());
        }
        if (tmpRespCode.equals("-1")) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(errormsg.toString());
        } else if (tmpRespCode.equals("0") && errormsg.length() > 0) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(errormsg.toString());
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }
}
